Imports System.Net.Mail

Module modEmail

    Public Function SendEmail(ByRef sErrDesc As String) As Long

        Dim sFuncName As String = "SendEmail"
        Dim sBody As String = String.Empty


        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Sarting function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Setting SMTP properties", sFuncName)

            Dim smtpClient As SmtpClient = New SmtpClient(p_oCompDef.sSMTPServer, p_oCompDef.sSMTPPort)

            smtpClient.UseDefaultCredentials = False
            smtpClient.Credentials = New System.Net.NetworkCredential(p_oCompDef.sSMTPUser, p_oCompDef.sSMTPPassword)

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network
            smtpClient.EnableSsl = True

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Function CreateDefaultMailMessage()", sFuncName)

            ' Split Email string based on ";"
            Dim sSendTo As String() = p_oCompDef.sEmailTo.Split(";")

            p_SyncDateTime = Format(Now, "dddd") & ", " & Format(Now, "MMM") & " " & Format(Now, "dd") & ", " & Format(Now, "yyyy") & " " & Format(Now, "HH:mm:ss")

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Building email message body steps .... ", sFuncName)

            sBody = sBody & "<div align=left style='font-size:10.0pt;font-family:Arial'>"
            sBody = sBody & p_SyncDateTime & " <br /><br />"
            sBody = sBody & " Dear Valued Customer,<br /><br /> Please find the attached Aging Receivable Report. <br /><br />"

            sBody = sBody & "<br/> Note: This email message is computer generated and it will be used internal purpose usage only.<div/>"

            Dim message As MailMessage = CreateDefaultMailMessage(p_oCompDef.sEmailFrom, sSendTo, p_oCompDef.sEmailSubject, sBody, sErrDesc)
            Dim userState As Object = message

            AddHandler smtpClient.SendCompleted, New SendCompletedEventHandler(AddressOf smtp_SendCompleted)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Sending Email Message", sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Sending Email Messages to : " & p_oCompDef.sEmailTo, sFuncName)
            smtpClient.Send(message)

            SendEmail = RTN_SUCCESS
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Function completed with Success", sFuncName)

        Catch ex As Exception
            SendEmail = RTN_ERROR
            sErrDesc = ex.Message
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Function completed with Error", sFuncName)
            Call WriteToLogFile(sErrDesc, sFuncName)
            Call WriteToLogFile("Failed sending email to : " & " " & p_oCompDef.sEmailTo, sFuncName)
        Finally

        End Try

    End Function

    Private Sub smtp_SendCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
        If (Not (e.Error Is Nothing)) Then
            Dim smessage As String = e.Error.Message
        End If
    End Sub

    Private Function CreateDefaultMailMessage(ByVal MailFrom As String, _
                                              ByVal MailTo As String(), _
                                              ByVal subject As String, _
                                              ByVal body As String, _
                                              ByRef sErrDesc As String) As MailMessage

        Dim message As MailMessage = New MailMessage()
        Dim sUploadFile As String = String.Empty
        Dim sFuncName As String = "CreateDefaultMailMessage"
        Dim sEmailAddress As String = String.Empty
        Dim AttachmentsDirInfo As System.IO.DirectoryInfo
        Dim AttachmentsFileInfo As System.IO.FileInfo() = Nothing
        Dim sAttachmentPath As String = String.Empty
        Dim sFileName As String = String.Empty
        Dim File As System.IO.FileInfo
        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Sarting function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Assigning Email Properties..", sFuncName)
            sAttachmentPath = System.IO.Directory.GetCurrentDirectory() & "\ReportsPDF"

            message.From = New MailAddress(MailFrom)

            For Each sEmailAddress In MailTo
                message.To.Add(New MailAddress(sEmailAddress))
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding Email Address" & ":  " & sEmailAddress, sFuncName)
            Next

            message.SubjectEncoding = System.Text.Encoding.UTF8
            message.Subject = subject
            message.BodyEncoding = System.Text.Encoding.UTF8
            message.Body = body
            message.IsBodyHtml = True

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding Attachments..", sFuncName)

            If Not String.IsNullOrEmpty(sAttachmentPath) Then
                If System.IO.Directory.Exists(sAttachmentPath) Then
                    AttachmentsDirInfo = New System.IO.DirectoryInfo(sAttachmentPath)
                    AttachmentsFileInfo = AttachmentsDirInfo.GetFiles("*.pdf*")
                End If
            End If

            For Each File In AttachmentsFileInfo
                message.Attachments.Add(New Attachment(File.FullName))
            Next

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed Successfully..", sFuncName)

            Return message

        Catch ex As Exception
            sErrDesc = ex.Message
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Function completed with Error", sFuncName)
            Call WriteToLogFile(sErrDesc, sFuncName)
            CreateDefaultMailMessage = Nothing
        Finally

        End Try

    End Function


End Module